/**
 * User: hou wanchun
 * Date: Feb 26, 2003
 * Time: 10:47:26 AM
 */
package com.ecomm.util;

import com.ecomm.exception.DBException;
import org.apache.commons.logging.Log;

import java.sql.Connection;
import java.util.Hashtable;

/**
 * 产生DB对象的工厂类
 */
public class DBFactory
{
    private static Log log = Logger.getLog(DBFactory.class);

    //保存DAO的静态hash
    private static Hashtable hashDAO = new Hashtable();

    //缺省的数据库连接
    private static String defaultConnection = Config.getString("database.default");

    /**
     * 取得对应缺省数据库的db连接
     *
     * @return
     */
    public static synchronized DB getDBInstance() throws DBException
    {
        return getDBInstance(defaultConnection);
    }

    public static synchronized DB getDBInstance(String name) throws DBException
    {
        DB db = null;
        DAO dao = (DAO) hashDAO.get(name);
        if (dao == null)
        {
            StringBuffer buf = new StringBuffer("database.");
            buf.append(name);
            buf.append(".daoadapterclass");
            try
            {
                String classname = Config.getString(buf.toString());
                Class c = Class.forName(classname);
                dao = (DAO) (c.newInstance());
                hashDAO.put(name, dao);
            }
            catch (Exception e)
            {
                log.error("不能成功实例化DAO类", e);
            }
        }
        if (dao != null)
        {
            db = new DBImpl(dao.getConnection());
        }
        return db;
    }

    public static synchronized DB getDBInstance(Connection conn)
    {
        return new DBImpl(conn);
    }
}
